using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Duckov.Modding;
using UnityEngine;

// ReSharper disable once CheckNamespace
public static class AutoConfigManager
{
    private static string _modName = string.Empty;
    private static bool _isInitialized;
    private static ModBehaviour? _modBehaviour;

    // 存储配置字段的完整信息
    private class ConfigFieldInfo
    {
        public FieldInfo Field { get; }
        public ConfigAttribute Attribute { get; }
        public string FullKey { get; }

        public ConfigFieldInfo(FieldInfo field, ConfigAttribute attribute, string fullKey)
        {
            Field = field;
            Attribute = attribute;
            FullKey = fullKey;
        }

        public bool UseSlider => Attribute.InputMaxLength <= 0 && Attribute.MinValue < Attribute.MaxValue;
    }

    private static readonly Dictionary<string, ConfigFieldInfo> ConfigFields =
        new Dictionary<string, ConfigFieldInfo>();

    // 特定配置变更回调字典
    private static readonly Dictionary<string, List<MethodInfo>> SpecificOnChangeCallbacks =
        new Dictionary<string, List<MethodInfo>>();

    // 全局变更回调列表
    private static readonly List<MethodInfo> GlobalOnChangeCallbacks =
        new List<MethodInfo>();

    // 延迟回调管理
    private static readonly Dictionary<string, Coroutine> DelayedCallbacks =
        new Dictionary<string, Coroutine>();

    private static readonly Dictionary<string, object> PendingValues =
        new Dictionary<string, object>();

    // 空回调
    private static Action<T> EmptyCallback<T>()
    {
        return (_) => { };
    }

    /// <summary>
    /// 初始化指定ModBehaviour所在命名空间下的所有配置类
    /// </summary>
    public static void InitializeAllConfigs(ModBehaviour modBehaviour)
    {
        if (_isInitialized) return;

        _modBehaviour = modBehaviour;
        _modName = modBehaviour.info.name;

        try
        {
            // 检查 ModSettingAPI 是否可用
            if (!ModSettingAPI.IsInit && !ModSettingAPI.Init(modBehaviour.info))
            {
                Debug.LogWarning($"[{_modName}][ACM] ModSettingAPI 不可用，跳过自动化配置初始化");
                return;
            }

            var assembly = Assembly.GetCallingAssembly();
            
            // 扫描程序集中指定命名空间下的所有类型
            foreach (var type in assembly.GetTypes())
            {
                // 检查类型是否在指定的命名空间下
                if (type.Namespace == _modName || (type.Namespace != null && type.Namespace.StartsWith(_modName + ".")))
                {
                    InitializeConfigClass(type, _modName);
                }
            }

            _isInitialized = true;
            Debug.Log($"[{_modName}][ACM] 自动化配置系统初始化完成，命名空间: {_modName}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"[{_modName}][ACM] 自动化配置系统初始化失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 初始化单个配置类
    /// </summary>
    private static void InitializeConfigClass(Type configType, string modNamespace)
    {
        // 检查类型是否包含配置字段、按钮或回调方法
        var hasConfigFields = false;
        foreach (var field in configType.GetFields(BindingFlags.Public | BindingFlags.NonPublic |
                                                   BindingFlags.Static))
        {
            if (field.GetCustomAttribute<ConfigAttribute>() == null) continue;

            hasConfigFields = true;
            break;
        }

        var hasButtonMethods = false;
        foreach (var method in configType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                                                     BindingFlags.Static))
        {
            if (method.GetCustomAttribute<ButtonAttribute>() == null) continue;

            hasButtonMethods = true;
            break;
        }

        var hasCallbackMethods = false;
        foreach (var method in configType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                                                     BindingFlags.Static))
        {
            if (method.GetCustomAttribute<OnChangeAttribute>() == null) continue;

            hasCallbackMethods = true;
            break;
        }

        // 如果没有配置相关的成员，跳过此类
        if (!hasConfigFields && !hasButtonMethods && !hasCallbackMethods)
        {
            return;
        }

        Debug.Log($"[{_modName}][ACM] 初始化配置类: {configType.Name}");

        // 先扫描并注册配置变更回调方法
        RegisterOnChangeCallbacks(configType, modNamespace);

        // 扫描并注册按钮方法
        RegisterButtonMethods(configType, modNamespace);

        // 扫描并注册配置字段
        foreach (var field in configType.GetFields(BindingFlags.Public | BindingFlags.NonPublic |
                                                   BindingFlags.Static))
        {
            var configAttr = field.GetCustomAttribute<ConfigAttribute>();
            if (configAttr == null) continue;

            // 先尝试加载已保存的值
            var loadedValue = LoadConfigValue(field, modNamespace, configAttr);
            if (loadedValue != null)
            {
                // 使用已保存的值设置字段
                field.SetValue(null, loadedValue);
                Debug.Log(
                    $"[{_modName}][ACM] 加载配置值: {GetConfigKey(modNamespace, field.Name, configAttr)} = {loadedValue}");
            }

            // 然后注册配置字段（使用已加载的值或默认值）
            RegisterConfigField(field, modNamespace, configAttr);
        }
    }

    /// <summary>
    /// 创建按钮控件
    /// </summary>
    private static void CreateButtonConfig(MethodInfo method, string modNamespace, ButtonAttribute buttonAttr)
    {
        // 生成按钮的唯一键
        var buttonKey = !string.IsNullOrEmpty(buttonAttr.ButtonKey)
            ? $"{modNamespace}_{buttonAttr.ButtonKey}"
            : $"{modNamespace}_{method.Name}";

        // 验证方法签名：必须是无参方法
        if (method.GetParameters().Length > 0)
        {
            Debug.LogWarning($"[{_modName}][ACM] 按钮方法必须是无参的: {method.DeclaringType?.Name}.{method.Name}");
            return;
        }

        // 创建按钮
        var success = ModSettingAPI.AddButton(
            buttonKey,
            buttonAttr.Description,
            buttonAttr.ButtonText,
            () =>
            {
                try
                {
                    method.Invoke(null, null);
                    Debug.Log($"[{_modName}][ACM] 按钮点击执行: {method.DeclaringType?.Name}.{method.Name}");
                }
                catch (Exception ex)
                {
                    Debug.LogError($"[{_modName}][ACM] 按钮执行失败 {buttonKey}: {ex.Message}");
                }
            }
        );

        if (success)
        {
            Debug.Log($"[{_modName}][ACM] 创建按钮: {buttonKey} -> {method.DeclaringType?.Name}.{method.Name}");
        }
        else
        {
            Debug.LogError($"[{_modName}][ACM] 创建按钮失败: {buttonKey}");
        }
    }

    /// <summary>
    /// 注册按钮控件
    /// </summary>
    private static void RegisterButtonMethods(Type configType, string modNamespace)
    {
        foreach (var method in configType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                                                     BindingFlags.Static))
        {
            var buttonAttr = method.GetCustomAttribute<ButtonAttribute>();
            if (buttonAttr != null)
            {
                CreateButtonConfig(method, modNamespace, buttonAttr);
            }
        }
    }

    /// <summary>
    /// 获取配置项的完整键名
    /// </summary>
    private static string GetConfigKey(string modNamespace, string fieldName, ConfigAttribute configAttr)
    {
        var configName = string.IsNullOrEmpty(configAttr.ConfigName) ? fieldName : configAttr.ConfigName;
        return $"{modNamespace}_{configName}";
    }

    /// <summary>
    /// 注册配置变更回调方法
    /// </summary>
    private static void RegisterOnChangeCallbacks(Type configType, string modNamespace)
    {
        foreach (var method in configType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                                                     BindingFlags.Static))
        {
            var onChangeAttrs = method.GetCustomAttributes<OnChangeAttribute>();
            foreach (var attr in onChangeAttrs)
            {
                if (string.IsNullOrEmpty(attr.ConfigName))
                {
                    // 监听所有配置变更
                    RegisterGlobalOnChangeCallback(method);
                }
                else
                {
                    // 监听特定配置字段变更
                    RegisterSpecificOnChangeCallback(method, attr.ConfigName, modNamespace);
                }
            }
        }
    }

    /// <summary>
    /// 注册监听所有配置变更的回调
    /// </summary>
    private static void RegisterGlobalOnChangeCallback(MethodInfo method)
    {
        // 验证方法签名：必须接受一个string参数（配置字段名）或无参数
        if (IsValidCallbackSignature(method))
        {
            GlobalOnChangeCallbacks.Add(method);
            Debug.Log($"[{_modName}][ACM] 注册全局配置变更回调: {method.DeclaringType?.Name}.{method.Name}()");
        }
        else
        {
            Debug.LogWarning(
                $"[{_modName}][ACM] 无效的全局配置变更回调签名: {method.DeclaringType?.Name}.{method.Name} - 必须是无参或接受一个string参数的方法");
        }
    }

    /// <summary>
    /// 注册监听特定配置字段变更的回调
    /// </summary>
    private static void RegisterSpecificOnChangeCallback(MethodInfo method, string configName, string modNamespace)
    {
        var fullConfigKey = $"{modNamespace}_{configName}";

        // 验证方法签名：必须是无参或接受一个string参数的方法
        if (IsValidCallbackSignature(method))
        {
            if (!SpecificOnChangeCallbacks.ContainsKey(fullConfigKey))
            {
                SpecificOnChangeCallbacks[fullConfigKey] = new List<MethodInfo>();
            }

            SpecificOnChangeCallbacks[fullConfigKey].Add(method);
            Debug.Log($"[{_modName}][ACM] 注册特定配置变更回调: {fullConfigKey} -> {method.DeclaringType?.Name}.{method.Name}()");
        }
        else
        {
            Debug.LogWarning(
                $"[{_modName}][ACM] 无效的特定配置变更回调签名: {method.DeclaringType?.Name}.{method.Name} - 必须是无参或接受一个string参数的方法");
        }
    }

    /// <summary>
    /// 验证回调方法签名
    /// </summary>
    private static bool IsValidCallbackSignature(MethodInfo method)
    {
        var parameters = method.GetParameters();
        return parameters.Length == 0 ||
               (parameters.Length == 1 && parameters[0].ParameterType == typeof(string));
    }

    /// <summary>
    /// 加载单个配置值
    /// </summary>
    private static object? LoadConfigValue(FieldInfo field, string modNamespace, ConfigAttribute configAttr)
    {
        var key = GetConfigKey(modNamespace, field.Name, configAttr);

        try
        {
            var success = false;
            object? loadedValue = null;

            if (field.FieldType.IsEnum)
            {
                // 枚举类型特殊处理
                success = ModSettingAPI.GetSavedValue(key, out string stringValue);

                if (!success || string.IsNullOrEmpty(stringValue)) return success ? loadedValue : null;
                // 找到对应的枚举值
                foreach (var enumValue in Enum.GetValues(field.FieldType))
                {
                    if (GetEnumDisplayName(field.FieldType, enumValue) != stringValue) continue;

                    loadedValue = enumValue;
                    break;
                }
            }
            else if (field.FieldType == typeof(bool))
            {
                success = ModSettingAPI.GetSavedValue(key, out bool boolValue);
                if (success) loadedValue = boolValue;
            }
            else if (field.FieldType == typeof(int))
            {
                success = ModSettingAPI.GetSavedValue(key, out int intValue);
                if (success) loadedValue = intValue;
            }
            else if (field.FieldType == typeof(float))
            {
                success = ModSettingAPI.GetSavedValue(key, out float floatValue);
                if (success) loadedValue = floatValue;
            }
            else if (field.FieldType == typeof(string))
            {
                success = ModSettingAPI.GetSavedValue(key, out string stringValue);
                if (success) loadedValue = stringValue;
            }
            else if (field.FieldType == typeof(KeyCode))
            {
                success = ModSettingAPI.GetSavedValue(key, out KeyCode keyCodeValue);
                if (success) loadedValue = keyCodeValue;
            }

            return success ? loadedValue : null;
        }
        catch (Exception ex)
        {
            Debug.LogError($"[{_modName}][ACM] 加载配置值失败 {key}: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 注册配置字段
    /// </summary>
    private static void RegisterConfigField(FieldInfo field, string modNamespace, ConfigAttribute configAttr)
    {
        var key = GetConfigKey(modNamespace, field.Name, configAttr);
        var currentValue = field.GetValue(null); // 现在这个值可能是已加载的值

        // 保存配置字段的完整信息
        var configFieldInfo = new ConfigFieldInfo
        (
            field,
            configAttr,
            key
        );

        ConfigFields[key] = configFieldInfo;

        Debug.Log($"[{_modName}][ACM] 注册配置字段: {key} = {currentValue}, AutoSave = {configAttr.AutoSave}");

        try
        {
            // 根据字段类型自动创建对应的配置项
            if (field.FieldType.IsEnum)
            {
                CreateEnumConfig(configFieldInfo, currentValue);
            }
            else if (field.FieldType == typeof(bool))
            {
                CreateBoolConfig(configFieldInfo, (bool)currentValue);
            }
            else if (field.FieldType == typeof(int))
            {
                CreateIntConfig(configFieldInfo, (int)currentValue);
            }
            else if (field.FieldType == typeof(float))
            {
                CreateFloatConfig(configFieldInfo, (float)currentValue);
            }
            else if (field.FieldType == typeof(string))
            {
                CreateStringConfig(configFieldInfo, (string)currentValue);
            }
            else if (field.FieldType == typeof(KeyCode))
            {
                CreateKeybindingConfig(configFieldInfo, (KeyCode)currentValue);
            }
            else
            {
                Debug.LogWarning($"[{_modName}][ACM] 不支持的配置类型: {field.FieldType} for field {field.Name}");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"[{_modName}][ACM] 注册配置字段失败 {field.Name}: {ex.Message}");
        }
    }

    /// <summary>
    /// 延迟执行配置变更回调
    /// </summary>
    private static void ExecuteDelayedOnChangeCallback(string configKey, object newValue)
    {
        // 如果已经有正在等待的协程，先停止它
        if (DelayedCallbacks.ContainsKey(configKey))
        {
            _modBehaviour?.StopCoroutine(DelayedCallbacks[configKey]);
            DelayedCallbacks.Remove(configKey);
        }

        // 保存当前值
        PendingValues[configKey] = newValue;

        // 启动新的延迟协程
        var coroutine = _modBehaviour?.StartCoroutine(DelayedCallbackCoroutine(configKey));
        if (coroutine != null)
        {
            DelayedCallbacks[configKey] = coroutine;
        }
        else
        {
            Debug.LogWarning(
                $"[{_modName}][ACM] 对 {configKey} 的配置变更回调时创建协程失败" +
                (!_modBehaviour ? ", ModBehaviour为空" : ""));
        }
    }

    /// <summary>
    /// 延迟回调协程
    /// </summary>
    private static IEnumerator DelayedCallbackCoroutine(string configKey)
    {
        // 等待1秒
        yield return new WaitForSeconds(1f);

        // 检查是否还有待处理的值
        if (!PendingValues.TryGetValue(configKey, out var finalValue)) yield break;

        // 设置最终值
        if (ConfigFields.TryGetValue(configKey, out var configFieldInfo))
        {
            configFieldInfo.Field.SetValue(null, finalValue);
            Debug.Log($"[{_modName}][ACM] 延迟配置变更: {configKey} = {finalValue}");
        }

        // 执行回调
        ExecuteOnChangeCallback(configKey);

        // 清理
        PendingValues.Remove(configKey);
        DelayedCallbacks.Remove(configKey);
    }

    /// <summary>
    /// 立即执行配置变更回调（用于非滑块配置）
    /// </summary>
    private static void ExecuteImmediateOnChangeCallback(string configKey, object newValue)
    {
        if (ConfigFields.TryGetValue(configKey, out var configFieldInfo))
        {
            configFieldInfo.Field.SetValue(null, newValue);
            Debug.Log($"[{_modName}][ACM] 立即配置变更: {configKey} = {newValue}");
        }

        ExecuteOnChangeCallback(configKey);
    }

    /// <summary>
    /// 执行配置变更回调
    /// </summary>
    private static void ExecuteOnChangeCallback(string configKey)
    {
        // 执行全局回调
        ExecuteGlobalOnChangeCallbacks(configKey);

        // 执行特定配置回调
        ExecuteSpecificOnChangeCallbacks(configKey);

        // 自动保存配置
        AutoSaveConfig(configKey);
    }

    /// <summary>
    /// 自动保存配置到磁盘
    /// </summary>
    private static void AutoSaveConfig(string configKey)
    {
        if (!ConfigFields.TryGetValue(configKey, out var configFieldInfo)) return;

        if (!configFieldInfo.Attribute.AutoSave) return;

        try
        {
            var currentValue = configFieldInfo.Field.GetValue(null);
            SaveSingleConfig(configFieldInfo, currentValue);
            Debug.Log($"[{_modName}][ACM] 自动保存配置: {configKey} = {currentValue}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"[{_modName}][ACM] 自动保存配置失败 {configKey}: {ex.Message}");
        }
    }

    /// <summary>
    /// 执行全局配置变更回调
    /// </summary>
    private static void ExecuteGlobalOnChangeCallbacks(string configKey)
    {
        // 执行监听所有配置变更的回调
        foreach (var method in GlobalOnChangeCallbacks)
        {
            ExecuteCallback(method, configKey);
        }
    }

    /// <summary>
    /// 执行特定配置变更回调
    /// </summary>
    private static void ExecuteSpecificOnChangeCallbacks(string configKey)
    {
        // 执行监听特定配置字段的回调
        if (!SpecificOnChangeCallbacks.TryGetValue(configKey, out var specificCallbacks)) return;

        foreach (var method in specificCallbacks)
        {
            ExecuteCallback(method, configKey);
        }
    }

    /// <summary>
    /// 执行单个回调方法
    /// </summary>
    private static void ExecuteCallback(MethodInfo method, string configKey)
    {
        try
        {
            var parameters = method.GetParameters();
            switch (parameters.Length)
            {
                case 0:
                    method.Invoke(null, null);
                    break;
                case 1 when parameters[0].ParameterType == typeof(string):
                    method.Invoke(null, new object[] { configKey });
                    break;
            }

            Debug.Log(
                $"[{_modName}][ACM] 执行配置变更回调: {configKey} -> {method.DeclaringType?.Name}.{method.Name}()");
        }
        catch (Exception ex)
        {
            Debug.LogError($"[{_modName}][ACM] 执行配置变更回调失败 {configKey}.{method.Name}: {ex.Message}");
        }
    }

    /// <summary>
    /// 创建枚举类型配置
    /// </summary>
    private static void CreateEnumConfig(ConfigFieldInfo configFieldInfo, object defaultValue)
    {
        var enumType = configFieldInfo.Field.FieldType;
        var options = (from object enumValue in Enum.GetValues(enumType)
            select GetEnumDisplayName(enumType, enumValue)
            into displayName
            select displayName ?? string.Empty).ToList();

        // 获取枚举的所有值及其显示名称

        // 使用下拉列表创建枚举配置
        ModSettingAPI.AddDropdownList(
            configFieldInfo.FullKey,
            configFieldInfo.Attribute.Description,
            options,
            GetEnumDisplayName(enumType, defaultValue) ?? string.Empty,
            (newValue) =>
            {
                // 找到对应的枚举值
                foreach (var enumValue in Enum.GetValues(enumType))
                {
                    if (GetEnumDisplayName(enumType, enumValue) != newValue) continue;
                    ExecuteImmediateOnChangeCallback(configFieldInfo.FullKey, enumValue);
                    break;
                }
            }
        );

        Debug.Log($"[{_modName}][ACM] 创建枚举配置: {configFieldInfo.FullKey}");
    }

    /// <summary>
    /// 获取枚举值的显示名称
    /// </summary>
    private static string? GetEnumDisplayName(Type enumType, object enumValue)
    {
        var enumName = Enum.GetName(enumType, enumValue);

        return enumType.GetField(enumName)?
            .GetCustomAttribute<EnumDisplayAttribute>()?
            .DisplayName ?? enumName;
    }

    /// <summary>
    /// 创建布尔类型配置
    /// </summary>
    private static void CreateBoolConfig(ConfigFieldInfo configFieldInfo, bool defaultValue)
    {
        ModSettingAPI.AddToggle(
            configFieldInfo.FullKey,
            configFieldInfo.Attribute.Description,
            defaultValue,
            (newValue) => { ExecuteImmediateOnChangeCallback(configFieldInfo.FullKey, newValue); }
        );

        Debug.Log($"[{_modName}][ACM] 创建布尔配置: {configFieldInfo.FullKey}");
    }

    /// <summary>
    /// 创建整数类型配置
    /// </summary>
    private static void CreateIntConfig(ConfigFieldInfo configFieldInfo, int defaultValue)
    {
        if (configFieldInfo.UseSlider)
        {
            // 滑块配置使用延迟回调
            ModSettingAPI.AddSlider(
                configFieldInfo.FullKey,
                configFieldInfo.Attribute.Description,
                defaultValue,
                (int)configFieldInfo.Attribute.MinValue,
                (int)configFieldInfo.Attribute.MaxValue,
                (newValue) => { ExecuteDelayedOnChangeCallback(configFieldInfo.FullKey, newValue); }
            );
        }
        else
        {
            // 输入框配置使用立即回调
            ModSettingAPI.AddInput(
                configFieldInfo.FullKey,
                configFieldInfo.Attribute.Description,
                defaultValue.ToString(),
                configFieldInfo.Attribute.InputMaxLength,
                (newValue) =>
                {
                    if (int.TryParse(newValue, out var intValue))
                    {
                        ExecuteImmediateOnChangeCallback(configFieldInfo.FullKey, intValue);
                    }
                }
            );
        }

        Debug.Log($"[{_modName}][ACM] 创建整数配置: {configFieldInfo.FullKey}");
    }

    /// <summary>
    /// 创建浮点数类型配置
    /// </summary>
    private static void CreateFloatConfig(ConfigFieldInfo configFieldInfo, float defaultValue)
    {
        if (configFieldInfo.UseSlider)
        {
            // 滑块配置使用延迟回调
            ModSettingAPI.AddSlider(
                configFieldInfo.FullKey,
                configFieldInfo.Attribute.Description,
                defaultValue,
                new Vector2(configFieldInfo.Attribute.MinValue, configFieldInfo.Attribute.MaxValue),
                (newValue) => { ExecuteDelayedOnChangeCallback(configFieldInfo.FullKey, newValue); },
                configFieldInfo.Attribute.FloatDecimalPlaces
            );
        }
        else
        {
            // 输入框配置使用立即回调
            ModSettingAPI.AddInput(
                configFieldInfo.FullKey,
                configFieldInfo.Attribute.Description,
                defaultValue.ToString($"F{configFieldInfo.Attribute.FloatDecimalPlaces}"),
                configFieldInfo.Attribute.InputMaxLength,
                (newValue) =>
                {
                    if (float.TryParse(newValue, out var floatValue))
                    {
                        ExecuteImmediateOnChangeCallback(configFieldInfo.FullKey, floatValue);
                    }
                }
            );
        }

        Debug.Log($"[{_modName}][ACM] 创建浮点数配置: {configFieldInfo.FullKey}");
    }

    /// <summary>
    /// 创建字符串类型配置
    /// </summary>
    private static void CreateStringConfig(ConfigFieldInfo configFieldInfo, string defaultValue)
    {
        var inputMaxValue = configFieldInfo.Attribute.InputMaxLength > 0
            ? configFieldInfo.Attribute.InputMaxLength
            : 10;

        ModSettingAPI.AddInput(
            configFieldInfo.FullKey,
            configFieldInfo.Attribute.Description,
            defaultValue,
            inputMaxValue,
            (newValue) => { ExecuteImmediateOnChangeCallback(configFieldInfo.FullKey, newValue); }
        );

        Debug.Log($"[{_modName}][ACM] 创建字符串配置: {configFieldInfo.FullKey}");
    }

    /// <summary>
    /// 创建按键绑定配置
    /// </summary>
    private static void CreateKeybindingConfig(ConfigFieldInfo configFieldInfo, KeyCode defaultValue)
    {
        ModSettingAPI.AddKeybinding(
            configFieldInfo.FullKey,
            configFieldInfo.Attribute.Description,
            defaultValue,
            (newValue) => { ExecuteImmediateOnChangeCallback(configFieldInfo.FullKey, newValue); }
        );

        Debug.Log($"[{_modName}][ACM] 创建按键绑定配置: {configFieldInfo.FullKey}");
    }

    /// <summary>
    /// 保存单个配置值
    /// </summary>
    private static void SaveSingleConfig(ConfigFieldInfo configFieldInfo, object currentValue)
    {
        try
        {
            if (configFieldInfo.Field.FieldType.IsEnum)
            {
                var displayName = GetEnumDisplayName(configFieldInfo.Field.FieldType, currentValue);
                ModSettingAPI.SetValue(configFieldInfo.FullKey, displayName, EmptyCallback<bool>());
            }
            else
            {
                // 使用泛型方法保存
                var setValueMethod = typeof(ModSettingAPI)
                    .GetMethod("SetValue")?
                    .MakeGenericMethod(configFieldInfo.Field.FieldType);

                setValueMethod?.Invoke(null,
                    new[] { configFieldInfo.FullKey, currentValue, EmptyCallback<bool>() });
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"[{_modName}][ACM] 保存单个配置失败 {configFieldInfo.FullKey}: {ex.Message}");
        }
    }

    /// <summary>
    /// 取消指定配置键的延迟回调
    /// </summary>
    /// <param name="configKey">配置键</param>
    public static void CancelDelayedCallback(string configKey)
    {
        if (DelayedCallbacks.TryGetValue(configKey, out var coroutine))
        {
            _modBehaviour?.StopCoroutine(coroutine);
            DelayedCallbacks.Remove(configKey);

            // 清理 PendingValues 中的相关值
            PendingValues.Remove(configKey);

            Debug.Log($"[{_modName}][ACM] 已取消配置键 {configKey} 的延迟回调");
        }
        else
        {
            Debug.LogWarning($"[{_modName}][ACM] 未找到配置键 {configKey} 的延迟回调");
        }
    }

    /// <summary>
    /// 返回所有等待中的回调的配置键
    /// </summary>
    /// <returns>等待中的回调的配置键列表</returns>
    public static List<string> GetAllPendingCallbackKeys()
    {
        return DelayedCallbacks.Keys.ToList();
    }

    public static void CancelAllDelayedCallback()
    {
        GetAllPendingCallbackKeys().ForEach(CancelDelayedCallback);
    }

    /// <summary>
    /// 保存所有配置到磁盘
    /// </summary>
    public static void SaveAllConfigs()
    {
        foreach (var (key, configFieldInfo) in ConfigFields)
        {
            try
            {
                var currentValue = configFieldInfo.Field.GetValue(null);
                SaveSingleConfig(configFieldInfo, currentValue);
                Debug.Log($"[{_modName}][ACM] 保存配置: {key} = {currentValue}");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[{_modName}][ACM] 保存配置失败 {key}: {ex.Message}");
            }
        }
    }
}